// packageA/mycomponent/goodsComponent/payDocument/payDocument.js
var app = getApp();
const fs = wx.getFileSystemManager();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    paidFile: {
      type: null,
    },
  },
  options: {
    addGlobalClass: true,
  },

  /**
   * 组件的初始数据
   */
  data: {
    timer:''
  },

  /**
   * 组件的方法列表
   */
  methods: {
    downloadClick(event) {
      let {id} = event.currentTarget.dataset?.item;
      if (this.data.timer) clearTimeout(this.data.timer); //防抖
      this.data.timer = setTimeout(() => {
        this.fileDown(id)
      }, 500);
    },
    fileDown(id) {
      wx.showLoading({
        title: '下载中',
      });
      let urlStr = app.getNetAddresss("plugin.paid-file.api.file.index");
      let json = {
        id: id
      };
      app._postNetWork({
        url: urlStr,
        data: json,
        success:  (resdata) => {
          let res = resdata.data;
          if (res.result == 1) {
            console.log(res.data);
            this.exportDownload(res.data?.url,res.data?.file_name);
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    },
    exportDownload(fileUrl,file_path) {
      // 下载文件
      this.deletContract(); //清除本地缓存 
      wx.downloadFile({
        url: fileUrl,
        success: function(res) {
          const tempFilePath = res.tempFilePath;
          wx.hideLoading();
          // 保存文件
          fs.saveFile({
            tempFilePath,
            filePath: `${wx.env.USER_DATA_PATH}/${file_path}`,
            success: function (res) {
              const savedFilePath = res.savedFilePath;
              // 打开文件
              wx.openDocument({
                filePath: savedFilePath,
                showMenu:true, //关键点
                success: function (res) {
                  console.log('打开文档成功')
                },
              });
            },
            fail: function (err) {
              wx.showToast({
                icon: 'none',
                title: '保存失败',
                duration: 1500
              });
              wx.hideLoading()
              console.log('保存失败：', err)
            }
          });
        },
        fail: function(err) {
          wx.showToast({
            icon: 'none',
            title: '下载失败',
            duration: 1500
          });
          console.log('下载失败：', err);
        },
      });
    },
    // 删除本地文件
    deletContract() {
      try {
        let file = wx.getFileSystemManager();
        file.readdir({
          dirPath:`${wx.env.USER_DATA_PATH}`,
          success: res => {
            let filesArr = res.files;
            if (filesArr.length > 0){
              for(let i in filesArr) {
                file.unlink({
                  filePath: `${wx.env.USER_DATA_PATH}/${filesArr[i]}`,
                  success: res => {
                    console.log(res);
                  },
                  fail: error => {
                    console.log(error);
                  },
                  complete: res => {
                    console.log(res);
                  }
                })
              }
            }
          }
        })
      } catch (error) {

      }
    },
  }
})
